<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

use think\facade\Cache;
use think\Db;

// 应用公共文件

// 数据缓存
function _cache($name = '')
{
    if ($name == 'db') {
        return true;
    }
}

// 权限列表
function _getCategory($cData = array())
{
    $table = 'category';
    $c1 = Db::name($table)->where('tid', 0)->order('des desc, id asc')->field('id, title')->select();
    $html = '';
    foreach ($c1 as $c1_1) {
        $checked = (empty($cData) || !in_array($c1_1['id'], $cData)) ? '' : 'checked="checked"';
//        $html .= "<h5>{$c1_1['title']}</h5>";
        $html .= "<h5><div class=\"radio i-checks\"><input type=\"checkbox\" name=\"data[]\" value=\"{$c1_1['id']}\" {$checked} /> {$c1_1['title']}</div></h5>";

        $c2 = Db::name($table)->where(['tid' => $c1_1['id'], 'hideleft' => '1'])->order('des desc, id asc')->field('id, title')->select();
        foreach ($c2 as $c2_1) {
            $html .= '<div class="form-group">';
            $html .= "<label class=\"col-sm-2 control-label\">{$c2_1['title']}</label>";

            $html .= '<div class="col-sm-10"><div class="radio i-checks">';

            $checked = (empty($cData) || !in_array($c2_1['id'], $cData)) ? '' : 'checked="checked"';
            $html .= '<label class="col-md-3">';
            $html .= "<input type=\"checkbox\" name=\"data[]\" value=\"{$c2_1['id']}\" {$checked} /> {$c2_1['title']}";
            $html .= '</label>';

            $c3 = Db::name($table)->where(['tid' => $c2_1['id']])->order('des desc, id asc')->field('id, title')->select();
            foreach ($c3 as $c3_1) {
                $checked = (empty($cData) || !in_array($c3_1['id'], $cData)) ? '' : 'checked="checked"';
                $html .= '<label class="col-md-3">';
                $html .= "<input type=\"checkbox\" name=\"data[]\" value=\"{$c3_1['id']}\" {$checked} /> {$c3_1['title']}";
                $html .= '</label>';
            }
            $html .= '</div></div>';

            $html .= '</div>';
        }
    }
    return $html;
}

// 输出option列表形式列表形式
function get_tree_option($data, $tid, $tid_name = 'tid')
{
    $stack = array($tid);
    $child = array();
    $added = array();
    $options = array();
    $obj = array();
    $loop = 0;
    $depth = -1;
    foreach ($data as $node) {
        $pid = $node[$tid_name];
        if (!isset($child[$pid])) {
            $child[$pid] = array();
        }
        array_push($child[$pid], $node['id']);
        $obj[$node['id']] = $node;
    }

    while (count($stack) > 0) {
        $id = $stack[0];
        $flag = false;
        $node = isset($obj[$id]) ? $obj[$id] : null;
        if (isset($child[$id])) {
            for ($i = count($child[$id]) - 1; $i >= 0; $i--) {
                array_unshift($stack, $child[$id][$i]);
            }
            $flag = true;
        }
        if ($id != $tid && $node && !isset($added[$id])) {
            $node['depth'] = $depth;
            $options[] = $node;
            $added[$id] = true;
        }
        if ($flag == true) {
            $depth++;
        } else {
            if ($node) {
                for ($i = count($child[$node[$tid_name]]) - 1; $i >= 0; $i--) {
                    if ($child[$node[$tid_name]][$i] == $id) {
                        array_splice($child[$node[$tid_name]], $i, 1);
                        break;
                    }
                }
                if (count($child[$node[$tid_name]]) == 0) {
                    $child[$node[$tid_name]] = null;
                    $depth--;
                }
            }
            array_shift($stack);
        }
        $loop++;
        if ($loop > 5000) return $options;
    }
    unset($child);
    unset($obj);
    return $options;
}

function sysConfig($name, $value = null)
{
    $cacheName = 'system_config';
    $config = Cache::get($cacheName, array());

    if (empty($value)) {
        $config = Db::name($cacheName)->column('key, value');
        Cache::set($cacheName, $config);
    }
    if ($value !== null) {
        $value = is_array($value) ? json_encode(trimValue($value)) : trim($value);
        if (isset($config[$name])) {
            $isSave = Db::name($cacheName)->where('key', $name)->update(['value' => $value]);
        } else {
            $isSave = Db::name($cacheName)->insert(['key' => $name, 'value' => $value]);
        }
        if ($isSave) {
            $config[$name] = $value;
            Cache::set($cacheName, $config);
        }
    }

    $data = '';
    if (isset($config[$name])) {
        $res = json_decode($config[$name], true);
        $data = is_array($res) ? $res : $config[$name];
    }

    return $data;
}

/**
 * User: Simony
 * Function:过滤空格
 * @param $data
 * @return array|string
 */
function trimValue($data)
{
    if (!is_array($data))
        return trim($data);
    return array_map('trimValue', $data);
}

/**
 * User:Simony
 * Function: 模块配置
 * @param $name
 * @param null $value
 * @return array|mixed|string
 * @throws \think\Exception
 * @throws \think\exception\PDOException
 */
function moduleConfig($name, $value = null)
{
    $cacheName = 'module_config';
    $config = Cache::get($cacheName, array());

    if (empty($value)) {
        $config = Db::name($cacheName)->column('key, value');
        Cache::set($cacheName, $config);
    }
    if ($value !== null) {
        $value = is_array($value) ? json_encode(trimValue($value)) : trim($value);
        if (isset($config[$name])) {
            $isSave = Db::name($cacheName)->where('key', $name)->update(['value' => $value]);
        } else {
            $isSave = Db::name($cacheName)->insert(['key' => $name, 'value' => $value]);
        }
        if ($isSave) {
            $config[$name] = $value;
            Cache::set($cacheName, $config);
        }
    }

    $data = '';
    if (isset($config[$name])) {
        $res = json_decode($config[$name], true);
        $data = is_array($res) ? $res : $config[$name];
    }

    return $data;
}

function randStr($length = 6, $type = 1, $code = '')
{
    if (strlen($code) >= $length) {
        return $code;
    }
    switch ($type) {
        case 1:
            $ascii = mt_rand(48, 57);
            break;
        case 2:
            $ascii = mt_rand(48, 122);
            if ($ascii >= 58 && $ascii <= 64 || $ascii >= 91 && $ascii <= 96) {
                return randStr($length, $type, $code);
            }
            break;
    }
    $code .= chr($ascii);
    return randStr($length, $type, $code);
}


/**
 * User:Simony
 * Function:
 * @param $code
 * @param string $message
 * @param string $result
 */
function ds_json_encode($code, $message = '', $result = [])
{
    $data = [
        $code => $message,
        'result' => $result,
    ];
    echo json_encode($data);
    exit;
}

/**
 * User:Simony
 * Function:
 * @param $code
 * @param string $message
 * @param string $result
 */
function ds_json($code, $message = '', $result = [])
{
    echo json_encode(['status' => $code, 'msg' => $message, 'result' => $result]);
    exit;
}

function ds_arr($code, $message, $result = [])
{
    return ['code' => $code, 'msg' => $message, 'result' => $result];
}


/**
 * User:Simony
 * Function: 保存oss路径到数据库的替换
 * @param $url
 * @return mixed
 */
function oss_save($url)
{
    if (empty($url)) {
        return $url;
    }
    $ossLogic = app\common\logic\OssLogic::getInstance();
    if ($ossLogic->isOssUrl($url)) {
        return str_replace($ossLogic->getSiteUrl(), app\common\logic\OssLogic::$prefix, $url);
    } else {
        return $url;
    }
}

/**
 * User:Simony
 * Function: 删除数组中元素的空格
 * @param $array
 * @return array|string
 */
function array_trim($array)
{
    if (!is_array($array))
        return trim($array);
    return array_map('array_trim', $array);
}

/**
 * User:Simony
 * Function: 配置
 * @param $name
 * @param null $value
 * @return array|mixed|string
 * @throws \think\Exception
 * @throws \think\exception\PDOException
 */
function settingConfig($name, $value = null)
{
    $cacheName = 'system_config';
    $config = Cache::get($cacheName, array());

    if (empty($value)) {
        $config = Db::name($cacheName)->column('key, value');
        Cache::set($cacheName, $config);
    }
    if ($value !== null) {
        $value = is_array($value) ? json_encode(array_trim($value)) : trim($value);
        if (isset($config[$name])) {
            $isSave = Db::name($cacheName)->where('key', $name)->update(['value' => $value]);
        } else {
            $isSave = Db::name($cacheName)->insert(['key' => $name, 'value' => $value]);
        }
        if ($isSave) {
            $config[$name] = $value;
            Cache::set($cacheName, $config);
        }
    }

    $data = '';
    if (isset($config[$name])) {
        $res = json_decode($config[$name], true);
        $data = is_array($res) ? $res : $config[$name];
    }

    return $data;
}

/**
 * User:Simony
 * Function:比较值
 * @param $val
 */
function compare_val($val, $compare_val)
{

    if (isset($val) && $val == $compare_val) {
        return true;
    } else {
        return false;
    }
}

/**
 * User:Simony
 * Function:按钮是否选中
 * @param $val
 */
function radio_checked($val, $compare_val)
{
    if (isset($val)) {
        return $val == $compare_val ? true : false;
    }
    return $compare_val == 0 ? true : false;
}

function api_json_encode($code, $msg, $data = [])
{
    echo json_encode(['code' => $code, 'msg' => $msg, 'data' => $data]);
    exit;
}

/**
 * User:Simony
 * Function: 获取汉字首字母
 * @param $s0
 * @return null|string
 */
function get_first_char($s0)
{   //获取单个汉字拼音首字母。注意:此处不要纠结。汉字拼音是没有以U和V开头的


    $fchar = ord($s0{0});
    if ($fchar >= ord("A") and $fchar <= ord("z")) return strtoupper($s0{0});
    $s1 = iconv("UTF-8", "GBK", $s0);
    $s2 = iconv("GBK", "UTF-8", $s1);
    $s = $s2 == $s0 ? $s1 : $s0;
    $asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
    if ($asc >= -20319 and $asc <= -20284) return "A";
    if ($asc >= -20283 and $asc <= -19776) return "B";
    if ($asc >= -19775 and $asc <= -19219) return "C";
    if ($asc >= -19218 and $asc <= -18711) return "D";
    if ($asc >= -18710 and $asc <= -18527) return "E";
    if ($asc >= -18526 and $asc <= -18240) return "F";
    if ($asc >= -18239 and $asc <= -17923) return "G";
    if ($asc >= -17922 and $asc <= -17418) return "H";
    if ($asc >= -17922 and $asc <= -17418) return "I";
    if ($asc >= -17417 and $asc <= -16475) return "J";
    if ($asc >= -16474 and $asc <= -16213) return "K";
    if ($asc >= -16212 and $asc <= -15641) return "L";
    if ($asc >= -15640 and $asc <= -15166) return "M";
    if ($asc >= -15165 and $asc <= -14923) return "N";
    if ($asc >= -14922 and $asc <= -14915) return "O";
    if ($asc >= -14914 and $asc <= -14631) return "P";
    if ($asc >= -14630 and $asc <= -14150) return "Q";
    if ($asc >= -14149 and $asc <= -14091) return "R";
    if ($asc >= -14090 and $asc <= -13319) return "S";
    if ($asc >= -13318 and $asc <= -12839) return "T";
    if ($asc >= -12838 and $asc <= -12557) return "W";
    if ($asc >= -12556 and $asc <= -11848) return "X";
    if ($asc >= -11847 and $asc <= -11056) return "Y";
    if ($asc >= -11055 and $asc <= -10247) return "Z";
    return NULL;
}


/**
 * User:Simony
 * Function:应用公共文件
 * @param $code
 * @param array $data
 * @return array
 */
function ajaxRuturn($code, $message, $data = [])
{
    $message = $message ?: getMessage($code);

    $result = ['code' => $code, 'message' => getMessage($code)];
    $result = (!empty($data)) ? $result['data'] = $data : $result;
    return $result;
}

/**
 * User:Simony
 * Function: 获取消息
 * @param $code
 * @return string
 */
function getMessage($code)
{
    $info = config('message.info');
    return (array_key_exists($code, $info) ? $info[$code] : '操作失败');
}

/**
 * User:Simony
 * 获取随机字符串
 * @param int $randLength 长度
 * @param int $addtime 是否加入当前时间戳
 * @param int $includenumber 是否包含数字
 * @return string
 */
function get_rand_str($randLength = 6, $addtime = 1, $includenumber = 0)
{
    if ($includenumber) {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNPQEST123456789';
    } else {
        $chars = 'abcdefghijklmnopqrstuvwxyz';
    }
    $len = strlen($chars);
    $randStr = '';
    for ($i = 0; $i < $randLength; $i++) {
        $randStr .= $chars[rand(0, $len - 1)];
    }
    $tokenvalue = $randStr;
    if ($addtime) {
        $tokenvalue = $randStr . time();
    }
    return $tokenvalue;
}


// 判断是否是微信浏览器
function is_weixin()
{
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
        return true;
    }
    return false;
}

/**
 * User: Simony
 * Function:CURL请求
 * @param $url 请求url地址
 * @param $method 请求方法 get post
 * @param null $postfields post数据数组
 * @param array $headers 请求header信息
 * @param bool|false $debug 调试开启 默认false
 */
function http_request($url, $method = "GET", $postfields = null, $headers = array(), $debug = false)
{
    $method = strtoupper($method);
    $ci = curl_init();
    /* Curl settings */
    curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
    curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
    curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 60); /* 在发起连接前等待的时间，如果设置为0，则无限等待 */
    curl_setopt($ci, CURLOPT_TIMEOUT, 7); /* 设置cURL允许执行的最长秒数 */
    curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
    switch ($method) {
        case "POST":
            curl_setopt($ci, CURLOPT_POST, true);
            if (!empty($postfields)) {
                $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
                curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
            }
            break;
        default:
            curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */
            break;
    }
    $ssl = preg_match('/^https:\/\//i', $url) ? TRUE : FALSE;
    curl_setopt($ci, CURLOPT_URL, $url);
    if ($ssl) {
        curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
        curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
    }
    //curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/
    curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ci, CURLOPT_MAXREDIRS, 1);/*指定最多的HTTP重定向的数量，这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/
    curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ci, CURLINFO_HEADER_OUT, true);
    /*curl_setopt($ci, CURLOPT_COOKIE, $Cookiestr); * *COOKIE带过去** */
    $response = curl_exec($ci);
    $requestinfo = curl_getinfo($ci);
    $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
    if ($debug) {
        echo "=====post data======\r\n";
        var_dump($postfields);
        echo "=====info===== \r\n";
        print_r($requestinfo);
        echo "=====response=====\r\n";
        print_r($response);
    }
    curl_close($ci);
    return $response;
}

function getMillisecond()
{
    list($t1, $t2) = explode(' ', microtime());
    return (float)sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);
}

function msec_to_sec($timestamp, $type = 'msec')
{
    if ($type == 'msec') {
        return sprintf('%.0f', $timestamp * 1000);
    } else {
        return sprintf('%.0f', $timestamp / 1000);
    }

}

/**
 * User: Simony
 * Function:获取月初月末时间戳
 * @param $month
 * @return array
 */
function get_month_start_end_time($month)
{
    $month_start = strtotime($month);//指定年月份月初时间戳

    $BeginDate = date('Y-m-01', strtotime($month));

    $EndDate = date('Y-m-d', strtotime("$BeginDate +1 month -1 day"));

    $month_end = strtotime("next day", strtotime($EndDate)) - 1;//指定年月份月末时间戳

    return [
        'start_time' => $month_start,
        'end_time' => $month_end
    ];

}